﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Kangaroo.Controls
{
    public static class TreeNodeHelper
    {
        public static bool IsLeafNode(this TreeNode node)
        {
            return node.Nodes.Count == 0;
        }

        public static bool IsRootNode(this TreeNode node)
        {
            return node.Parent == null;
        }

        public static TreeNode GetFirstLeaf(this TreeNode node)
        {
            while(node.Nodes.Count > 0)
            {
                node = node.FirstNode;
            }
            return node;
        }

        public static void SelectFirstNode(this TreeView treeView)
        {
            if(treeView.Nodes.Count > 0)
            {
                treeView.SelectedNode = GetFirstLeaf(treeView.Nodes[0]);
            }
        }

        public static void SetTreeNodes(this TreeView treeView, TreeNode[] nodes)
        {
            SetTreeNodes(treeView, nodes, null);
        }

        public static void SetTreeNodes(this TreeView treeView, TreeNode[] nodes, TreeNode nodeToBeSelected)
        {
            treeView.Nodes.Clear();
            treeView.Nodes.AddRange(nodes);
            if (nodeToBeSelected == null)
            {
                SelectFirstNode(treeView);                
            }
            else
            {
                treeView.SelectedNode = nodeToBeSelected;
            }
        }

        public static IEnumerable<TreeNode> EnumerateLeaves(this TreeNodeCollection nodes)
        {
            return EnumerateLeaves(nodes.Cast<TreeNode>());
        }

        public static IEnumerable<TreeNode> EnumerateLeaves(this IEnumerable<TreeNode> nodes)
        {
            foreach (var node in nodes)
            {
                if (node.IsLeafNode())
                {
                    yield return node;
                }
                else
                {
                    foreach (var leaf in  node.Nodes.EnumerateLeaves())
                    {
                        yield return leaf;
                    }
                }
            }
        }
    }
}
